const baseUrl = Vue.prototype.baseUrl || 'http://192.168.110.2:8080'; // 替换为你的服务器IP地址

const messageApi = {
	// 发送消息
	send(data) {
		const userInfo = uni.getStorageSync('userInfo');
		if (userInfo === undefined || userInfo.id === undefined) {
			return Promise.reject(new Error('请先登录'));
		}
		console.log('baseUrl:', baseUrl); // 添加日志
		console.log('发送消息数据:', data); // 添加日志

		const messageData = {
			senderId: userInfo.id,
			receiverId: data.toUserId,
			content: data.content,
			type: data.type || 'text',
			productId: data.productId || 0
		};
		console.log('发送到后端的数据:', messageData); // 添加日志

		return uni.request({
			url: baseUrl + '/wx/message/send',
			method: 'POST',
			header: {
				'content-type': 'application/json',
				'X-Litemall-Token': uni.getStorageSync('token')
			},
			data: messageData,
			timeout: 10000 // 设置超时时间
		}).then(res => {
			console.log('发送消息响应:', res); // 添加日志
			return res;
		}).catch(err => {
			console.error('发送消息错误:', err); // 添加错误日志
			throw err;
		});
	},

	// 获取历史消息
	getHistory(partnerId, page = 1, size = 20) {
		const userInfo = uni.getStorageSync('userInfo');
		const token = uni.getStorageSync('token'); // 添加 token
		if (userInfo === undefined || userInfo.id === undefined) {
			return Promise.reject(new Error('请先登录'));
		}
		return uni.request({
			url: baseUrl + '/wx/message/list',
			method: 'GET',
			header: {
				'X-Litemall-Token': token // 修改为正确的 token header
			},
			data: {
				userId: userInfo.id,
				partnerId: partnerId,
				page: page,
				size: size
			}
		});
	},

	// 获取聊天列表
	getChatList() {
		const userInfo = uni.getStorageSync('userInfo');
		if (userInfo === undefined || userInfo.id === undefined) {
			return Promise.reject(new Error('请先登录'));
		}

		return uni.request({
			url: baseUrl + '/wx/message/chatList',
			method: 'GET',
			header: {
				'content-type': 'application/json',
				'X-Litemall-Token': uni.getStorageSync('token')
			},
			data: {
				userId: userInfo.id // 添加 userId 参数
			}
		});
	},

	// 获取聊天详情
	getChatDetail(partnerId) {
		return uni.request({
			url: baseUrl + '/wx/message/chatDetail',
			method: 'GET',
			header: {
				'X-Litemall-Token': uni.getStorageSync('token')
			},
			data: {
				partnerId: partnerId
			}
		});
	},

	// 创建聊天
	createChat(data) {
		return uni.request({
			url: baseUrl + '/wx/message/create',
			method: 'POST',
			header: {
				'content-type': 'application/json',
				'X-Litemall-Token': uni.getStorageSync('token')
			},
			data: data
		});
	}
};

export default messageApi;